package com.katze.boot.plugins.redis.aspect;

import com.katze.boot.plugins.redis.RedisTemplateManager;
import com.katze.boot.plugins.redis.interfaces.SelectDB;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 说  明：
 * 作  者：zf.zeng
 * 日  期：2022-11-10 (星期四)
 **/
@Aspect
@Component
@ConditionalOnProperty(prefix = "spring.data.redis.databases", name = "dynamic-select", havingValue = "true")
public class SelectAspect {
    private static final Logger log = LoggerFactory.getLogger(SelectAspect.class);

    @Pointcut("@annotation(com.katze.boot.plugins.redis.interfaces.SelectDB)")
    public void pointcut() {
        // do nothing
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            SelectDB selectDBAnnotation = method.getAnnotation(SelectDB.class);
            log.info("Redis switch database: {} to {}", RedisTemplateManager.getDatabase(), selectDBAnnotation.value());
            RedisTemplateManager.setDatabase(selectDBAnnotation.value());
            return point.proceed();
        } finally {
            RedisTemplateManager.setDatabase(null);
        }
    }

}
